<?php
/**
 * Created by PhpStorm.
 * User: N
 * Date: 2017/12/13
 * Time: 15:17
 */
namespace common\models;

use Yii;
use yii\base\Model;
use common\models\Models;
use backend\modules\content\models\Sitemodel;
use backend\modules\content\models\Modelfield;
use yii\db\ActiveRecord;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;


/**
 * This is the model class for table "category".
 *
 * @property string $catid
 * @property string $siteid
 **/
class Content extends ActiveRecord
{
    public static $table='news';

    //数据库表名
    public static function tableName()
    {
        return '{{%'.self::$table.'}}';
    }


    public static function setTable($modelid=1){
        //通过model获取表名，赋值
        if($modelid !=1)
        {
            $main = new Models;
            $data = $main->find()->where(['modelid'=>$modelid])->one();
        }

        self::$table=(isset($data->tablename) && !empty($data->tablename))?$data->tablename:'news';
    }

    /**
     * 设置模型
     * 通过modelid来选择模型，通过设置数据表，来实现转换
     */
    public static function setModel($modelid=1){
        //通过model获取表名，赋值
        if($modelid !=1)
        {
            $main = new Models;
            $data = $main->find()->where(['modelid'=>$modelid])->one();
        }

        self::$table=isset($data->tablename)?$data->tablename:'news';
    }

    public function rules()
    {
        //处理模型中相关字段
        $fields = $this->getfields();
        $temp_field = [];
        if($fields){
            foreach($fields as $v){
                $temp_setting = json_decode($v['setting']);
                $temp_field[] = [$v['field'],'default','value'=>$temp_setting->defaultvalue?$temp_setting->defaultvalue:''];
            }
        }

        $base = [
            [['catid','title','content'],'required','message'=>'必填'],
            [['keywords','username','description','updatetime','inputtime','thumb','posids'],'default','value'=>'']
        ];
        return array_merge($base,$temp_field);
    }

    public function beforeSave($insert){
        if($insert){
            //插入时补充操作
            $this->inputtime = time();
        }else{
            //修改时补充操作

        }
        //添加修改时必定修改信息
        $this->updatetime = time();
        if(empty($this->description)){//简介，描述
            $this->description = mb_strcut(strip_tags($this->content),0,200);
        }

//        $this->status = $this->status?99:$this->status;

        //自动提取正文中第x张图为缩略图
        if($this['thumb'] == '' && isset($this->content)) {
            $this->content = $this->content ? $this->content : stripslashes($this->content);
            $auto_thumb_no = isset($_POST['auto_thumb_no'])?intval($_POST['auto_thumb_no'])-1:0;
            if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $this->content, $matches)) {
                $this->thumb = isset($matches[3][$auto_thumb_no])?$matches[3][$auto_thumb_no]:$matches[3][0];
            }
        }
        return true;

    }

    public function attributeLabels()
    {
        //模型中相关字段处理
        $fields = $this->getfields();
        $extro = [];
        if($fields){
            foreach($fields as $v){
                $extro[$v['field']] = $v['name'];
            }
        }

        $base =  [
            'title' => '新闻标题',
            'catid' => '栏目名称',
            'content'=>'内容',
            'thumb' => '上传图片',
            'description' => '描述',
            'listorder'=>'排序',
            'updatetime'=>'修改时间',
            'inputtime'=>'添加时间',
            'keywords'=>'关键字',
            'posids'=>'推荐',
            'username'=>'作者',
            'status'=>'状态'
        ];

        return array_merge($base,$extro);
    }

    /**
     * 查询当前模型下的相关字段信息
     * @return array|ActiveRecord[]
     */
    public function getfields(){
        //查询该模型下相关字段
        $modelid = Sitemodel::find()->where(['tablename'=>self::$table])->select('modelid')->one();
        $fields = Modelfield::find()->where(['modelid'=>$modelid,'issystem'=>0])->select('field,name,isunique,listorder,setting')->asArray()->all();
        return $fields;
    }

    /**
     * 将一维数组转换为字符串
     * 字符串样式为 str,str,str
     */
    public static function array2string($arr)
    {
        if(!is_array($arr) || !$arr)
        {
            return $arr;
        }
        $str = '';
        foreach($arr as $a)
        {
            $str.= $str ? ",$a" : $a;
        }
        return $str;
    }
    
    /**
	 * 执行sql查询
	 * @param $where 		查询条件[例`name`='$name']
	 * @param $data 		需要查询的字段值[例`name`,`gender`,`birthday`]
	 * @param $limit 		返回结果范围[例：10或10,10 默认为空]
	 * @param $order 		排序方式	[默认按数据库默认方式排序]
	 * @param $group 		分组方式	[默认为空]
	 * @param $key          返回数组按键名排序
	 * @return array		查询结果集数组
	 */
	public function select($where = '', $data = '*', $limit = '', $order = '', $group = '', $key='')
    {
        $data = self::array2string($data);

        $result = self::find()->select($data)->where($where)->limit($limit)->orderBy($order)->groupBy($group)->asArray()->all();

        return $result;

    }

	/**
	 * 获取单条记录查询
	 * @param $where 		查询条件
	 * @param $data 		需要查询的字段值[例`name`,`gender`,`birthday`]
	 * @param $order 		排序方式	[默认按数据库默认方式排序]
	 * @param $group 		分组方式	[默认为空]
	 * @return array/null	数据查询结果集,如果不存在，则返回空
	 */
	public function get_one($where = '', $data = '*', $order = '', $group = '') {
        $data = self::array2string($data);
        $result = self::find()->select($data)->where($where)->orderBy($order)->groupBy($group)->asArray()->one();
        return $result;
        
	}

	/**
	 * 执行更新记录操作
	 * @param $data 		要更新的数据内容，参数可以为数组也可以为字符串，建议数组。
	 * 						为数组时数组key为字段值，数组值为数据取值
	 * 						为字符串时[例：`name`='phpcms',`hits`=`hits`+1]。
	 *						为数组时[例: array('name'=>'phpcms','password'=>'123456')]
	 *						数组的另一种使用array('name'=>'+=1', 'base'=>'-=1');程序会自动解析为`name` = `name` + 1, `base` = `base` - 1
	 * @param $where 		更新数据时的条件,可为数组或字符串
	 * @return boolean
	 */
    public function updatedata($data, $where = '')
    {  
        $result = self::find()->where($where)->one();
        if(is_array($data))
        {
            foreach($data as $key=>$value)
            {
                $result->$key = $value;
            }
            
            if($result->save())
            {
                return true;
            }
            else
            {
                return false;
            }
        }
            
        
    }

	/**
	 * 执行添加记录操作
	 * @param $data 		要增加的数据，参数为数组。数组key为字段值，数组值为数据取值
	 * @param $return_insert_id 是否返回新建ID号
	 * @param $replace 是否采用 replace into的方式添加数据
	 * @return boolean
	 */
    public function insertdata($data, $return_insert_id = false, $replace = false) 
    {
        $result = new Content();
        if(is_array($data))
        {
            foreach($data as $key=>$value)
            {
                $result->$key = $value;
            }
            
            if($result->save($runValidation = true, $attributeNames = null))
            {
                return true;
            }
            else
            {
                return false;
            }
        }        
    }

	/**
	 * 执行删除记录操作
	 * @param $where 		删除数据条件,不充许为空。
	 * @return boolean
	 */
    public function deletedata($where) 
    {
        $result = self::find()->where($where)->one();
        $result->status='0';
        if($result->save())
        {
            return true;
        }
        else
        {
            return false;
        }
        
    }

    /**
	 * 查询多条数据并分页
	 * @param $where
	 * @param $order
	 * @param $page
	 * @param $pagesize
	 * @return unknown_type
	 */
    public function listinfo($where = '', $order = '', $page = 1, $pagesize = 20, $key='', $setpages = 10,$urlrule = '',$array = array(), $data = '*') 
    {
		$number = $this->count($where);
		$page = max(intval($page), 1);
		$offset = $pagesize*($page-1);
		$array = array();
        if ($number > 0) 
        {
			return $this->select($where, $data, "$offset, $pagesize", $order, '', $key);
        } 
        else 
        {
			return array();
        }
        /*
        $data = Comment::find()->andWhere($where);
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => '$pagesize']);
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        */
    }

	
	/**
	 * 计算记录数
	 * @param string/array $where 查询条件
	 */
    public function count($where = '') 
    {
        $result = self::find()->where($where)->count();
		return $result;
	}

    public function test()
    {
        echo 1;
    }

    /**
     * 审核
     * @param $catid 栏目ID
     * @param $status 文章状态
     * @return $status 文章状态
     */
    public function pass($catid,$status)
    {
        //找出栏目工作流
        $cate = Category::find()->where(['catid'=>$catid])->one();
        $cate_setting = $cate->setting;
        //判断工作流状态是否为pass，若是pass状态，直接返回
        if($status==Yii::$app->params['Audit_Pass'])
        {
            return $status;
        }
        $pass = array(
            //一级审核流程
            '1'=>array(
                '0'=>Yii::$app->params['Audit_Pass'],
            ),
            //二级审核流程
            '2'=>array(
                '0'=>Yii::$app->params['Audit_One'],
                Yii::$app->params['Audit_One']=>Yii::$app->params['Audit_Pass'],
            ),
            //三级审核流程
            '3'=>array(
                '0'=>Yii::$app->params['Audit_One'],
                Yii::$app->params['Audit_One']=>Yii::$app->params['Audit_Two'],
                Yii::$app->params['Audit_Two']=>Yii::$app->params['Audit_Pass'],
            ),
        );
        //判断状态是否存在       
        $r = isset($pass[$cate_setting][$status])?$pass[$cate_setting][$status]:Yii::$app->params['Audit_False'];
        
        return $r;
        //此方法局限性太大，需要再斟酌一下
        /*
        //对栏目工作流进行判断
        switch($cate_setting)
        {
            //当工作流审核为1级时
            case 1:
                //将状态设置为PASS
                $status=Yii::$app->params['Audit_Pass'];
                break;
            //当工作流审核为2级时
            case 2:
                //将状态动态设置
                $status = $status + $num*Yii::$app->params['Audit_One'];
                break;
            //当工作流审核为3级时
            case 3:
                //将状态动态设置
                $status = $num*Yii::$app->params['Audit_One'];
                break;
            //当不需要审核时
            default:
                //将状态设置为PASS
                $status = Yii::$app->params['Audit_Pass'];
                break;
        }
        
        //返回状态值
        return $status;
        */
    }
    public function refuse()
    {
        return $status = Yii::$app->params['Audit_Fail'];
    }

}